package com.kedacom.ctsp.authz.oauth2.util;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.DataInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * @remark:
 * @ClassName RsaKeyHelper
 * @Author fenghaiju
 * @date 2018/6/29
 **/
public class RsaKeyHelper {
    private KeyPairGenerator keyPairGenerator = null;

    private static RsaKeyHelper rsaKeyHelper;

    public synchronized void initKeyPairGenerator() {

        try {
            if (keyPairGenerator == null) {
                keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            }
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
    }

    public RsaKeyHelper() {
        initKeyPairGenerator();
    }

    public static RsaKeyHelper getInstance() {
        if (rsaKeyHelper == null) {
            rsaKeyHelper = new RsaKeyHelper();
        }
        return rsaKeyHelper;
    }

    /**
     * 获取公钥
     *
     * @param publicKey
     * @return
     * @throws Exception
     */
    public PublicKey getPublicKey(byte[] publicKey) throws Exception {
        X509EncodedKeySpec spec = new X509EncodedKeySpec(publicKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePublic(spec);
    }

    /**
     * 获取密钥
     *
     * @param privateKey
     * @return
     * @throws Exception
     */
    public PrivateKey getPrivateKey(byte[] privateKey) throws Exception {
        PKCS8EncodedKeySpec spec = new PKCS8EncodedKeySpec(privateKey);
        KeyFactory kf = KeyFactory.getInstance("RSA");
        return kf.generatePrivate(spec);
    }

    public Map<String, byte[]> generateKey(String password) throws IOException, NoSuchAlgorithmException {

        SecureRandom secureRandom = new SecureRandom(password.getBytes());
        if (keyPairGenerator == null) {
            keyPairGenerator = KeyPairGenerator.getInstance("RSA");
        }
        keyPairGenerator.initialize(1024, secureRandom);
        KeyPair keyPair = keyPairGenerator.genKeyPair();
        byte[] publicKeyBytes = keyPair.getPublic().getEncoded();
        byte[] privateKeyBytes = keyPair.getPrivate().getEncoded();
        Map<String, byte[]> map = new HashMap<>();
        map.put("pub", publicKeyBytes);
        map.put("pri", privateKeyBytes);
        return map;
    }

    public static String toHexString(byte[] b) {
        return (new BASE64Encoder()).encodeBuffer(b);
    }

    public static final byte[] toBytes(String s) throws IOException {
        return (new BASE64Decoder()).decodeBuffer(s);
    }

}
